package com.huiquan.icd.service;

import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.huiquan.analysis.domain.User;
import com.huiquan.framework.base.BaseService;
import com.huiquan.framework.base.ReturnCode;
import com.huiquan.framework.base.ReturnData;
import com.huiquan.framework.utils.ExcelUtil;
import com.huiquan.framework.utils.GetListUtil;
import com.huiquan.framework.utils.RespHeaderUtil;
import com.huiquan.framework.utils.ReturnUtil;
import com.huiquan.icd.dao.IcdDiseaseGaogeDao;
import com.huiquan.icd.domain.IcdDiseaseGaoge;
import com.huiquan.medicine.dao.MedicineDao;

@Service
public class IcdDiseaseGaogeService extends BaseService {

	
	@Autowired
	private IcdDiseaseGaogeDao icdDiseaseGaogeDao;
	@Autowired
	private MedicineDao medicineDao;
	public ModelAndView list(Integer start, String codeSearch, String nameSearch,
			String exactSearchFlag,String modifyFlag ,String countPerPageStr) {
		boolean exactFlag = exactSearchFlag != null && exactSearchFlag.equals("1");

		Map<String, Object> param = new HashMap<>();
		if (codeSearch != null && !codeSearch.isEmpty()) {
			param.put("disease", exactFlag ? codeSearch : "%" + codeSearch + "%");
		}
		if (nameSearch != null && !nameSearch.isEmpty()) {
			param.put("gaoge", exactFlag ? nameSearch : "%" + nameSearch + "%");
		}
		
		int totalSize = icdDiseaseGaogeDao.retrieveSize(param);

		Map<String, Integer> pageNo = new HashMap<>();
		if (countPerPageStr != null && !countPerPageStr.isEmpty()) {
			int countPerPage = Integer.parseInt(countPerPageStr);
			pageNo = GetListUtil.getPageNoParam(totalSize, start+"", countPerPage);
			param.put("countPerPage", countPerPage);
		} else {
			pageNo = GetListUtil.getPageNoParam(totalSize, start+"");
		}
		int endPage = pageNo.get("endPage");
		start = pageNo.get("start");
		int startIndex = pageNo.get("startIndex");

		List<IcdDiseaseGaoge> list = new ArrayList<>();

		if (startIndex < totalSize) {
			param.put("startIndex", startIndex);
			list = icdDiseaseGaogeDao.retrievesList(param);
		}
		Map<String, String> showSearch = new LinkedHashMap<>();
		showSearch.put("codeSearch", "疾病");
		showSearch.put("nameSearch", "高歌疾病");

		Map<String, String> searchMap = new HashMap<>();
		searchMap.put("codeSearch", codeSearch);
		searchMap.put("nameSearch", nameSearch);
		Map<String, Object> map = GetListUtil.getReturnMap2(totalSize, start, startIndex, endPage, list, searchMap);
		map.put("showSearch", showSearch);
		map.put("showSearchValue", searchMap);
		map.put("modifyFlag", modifyFlag);
		map.put("exactSearchFlag", exactSearchFlag);
		return new ModelAndView("icd/index", map);
	}
 
	public void codeExport(HttpServletResponse resp) throws Exception {
		Map<String, Object> param = new HashMap<>();
		// 获取已校验code列表
		List<IcdDiseaseGaoge> codeList = icdDiseaseGaogeDao.retrievesList(param);
		LOGGER.info("codeExport get list success!size=" + codeList.size());

		// 设置respons的头信息
		RespHeaderUtil.setXlsxResp(resp, "gaoge");
		
		// 创建文档
		XSSFWorkbook workbook = new XSSFWorkbook();
		Sheet sheet = workbook.createSheet("gaoge"); // 创建Sheet

		// 写入标题行
		ExcelUtil.setTitleToFirstRow(workbook,
				new String[] { "疾病名称", "高歌疾病名称" });

		// 循环写入数据
		IcdDiseaseGaoge code = null;
		Row row = null;
		for (int i = 0; i < codeList.size(); i++) {
			code = codeList.get(i);

			row = sheet.createRow(i + 1);

			List<String> cellValues = new ArrayList<>();
			cellValues.add(code.getDisease());
			cellValues.add(code.getGaoge());

			addCell(row, cellValues);
		}
		LOGGER.info("codeExport create excel success!");

		OutputStream os = resp.getOutputStream();
		workbook.write(os);
		workbook.close();

		os.close();
	}

	private void addCell(Row row, List<String> cellValues) {
		if (cellValues.size() > 0) {
			Cell cell = null;
			for (int i = 0; i < cellValues.size(); i++) {
				String cellValue = cellValues.get(i);
				cell = row.createCell(i);
				cell.setCellValue(cellValue);
			}
		}
	}
	public ReturnData diseaseImport( MultipartFile mFile, User user) throws Exception {

		// 获取文件流，解析文件
		InputStream inputStream = mFile.getInputStream();

		Workbook workbook = new XSSFWorkbook(inputStream);
		Sheet sheet = workbook.getSheetAt(0);
		//分隔符
		char flag = 3;
		//获取所有疾病名称的集合
		List<String > diseaseNames = icdDiseaseGaogeDao.getAllDiseaseName();
		StringBuffer errorMsg = new StringBuffer(); // 记录下错误的疾病名称
		List<String> allValue = new ArrayList<>(); // 记录下所有的疾病和高歌疾病对应关系用于判断是否重复导入
		Map<String, String > allMap = new HashMap<>();
		//保存的记录
		List<IcdDiseaseGaoge> list = new ArrayList<>();
		//行数
		int j = 1;
		
		for (Row row : sheet) {
			//疾病名称-高歌疾病 用于判断是否重复
			StringBuffer rowDisease = new StringBuffer();
			int i = 0;
			//取出每一行记录
			for (Cell cell : row) {
				//第一行跳过
				if(j==1){
					break;
				}
				cell.setCellType(Cell.CELL_TYPE_STRING);
				String word = cell.getStringCellValue().trim();
				if (!word.isEmpty()) {
					if(i==0){
						rowDisease.append(word);
					}else if(i==1){
						rowDisease.append(flag).append(word);
					}
				}
				i++;
			}
			if(rowDisease != null && rowDisease.length()>0){
				String[] disease  = rowDisease.toString().split(flag+"");
				//取到一行记录后判断是否重复
				if(allMap.containsKey(rowDisease.toString())){
						//如果有重复就添加到重复中  不报错但不添加
						j++;
						continue;
				}else{
					allMap.put(rowDisease.toString(), "1");
				}
				//判断疾病是否在疾病维表中出现
				if(!diseaseNames.contains(disease[0])){
					//如果不存在则是错误的
					errorMsg.append(rowDisease).append(",");
					j++;
					continue;
				}
				IcdDiseaseGaoge value = new IcdDiseaseGaoge();
				value.setDisease(disease[0]);
				value.setGaoge(disease[1]);
				value.setModifierId(user.getUserId()+"");
				list.add(value);
				allValue.add(rowDisease.toString());
			}
			j++;
		}

		if (errorMsg.length() > 0 ) {
			// 表示有重复的词语，报错
			LOGGER.info(errorMsg.toString().substring(0, errorMsg.length()-1));
			workbook.close();
			inputStream.close();
			ReturnCode rc = ReturnCode.DYNAMIC_DESC_EXCEPTION;
			rc.setDesc("导入失败,这些疾病不在疾病维表中:"+errorMsg.toString().substring(0, errorMsg.length()-1).replace(flag+"", "|"));
			return ReturnUtil.fail(rc);
		}

		// 删除数据库数据
		icdDiseaseGaogeDao.deleteAll();
		//批量添加
		icdDiseaseGaogeDao.batchInsert(list);

		workbook.close();
		inputStream.close();

		return ReturnUtil.success();
	}
	
	
	public ReturnData addGaogeDisease(String newGaogeName , String newDiseaseName,  User user) {
			//查询疾病维表是否有该疾病
			int count = medicineDao.selectIcdDiseaseCountByName(newDiseaseName);
			Map<String, Object> param = new HashMap<>();
			param.put("disease", newDiseaseName);
			param.put("gaoge", newGaogeName);
			int totalSize = icdDiseaseGaogeDao.retrieveSize(param);
			if(totalSize>0){
				ReturnCode rc = ReturnCode.DYNAMIC_DESC_EXCEPTION;
				rc.setDesc("不允许添加重复记录");
				return ReturnUtil.fail(rc);
			}
			if(count==0){
				ReturnCode rc = ReturnCode.DYNAMIC_DESC_EXCEPTION;
				rc.setDesc("疾病名称必须为疾病维表中的疾病名称");
				return ReturnUtil.fail(rc);
			}
			icdDiseaseGaogeDao.addGaogeDisease(user.getUserId(), newDiseaseName, newGaogeName);
		return ReturnUtil.success();
	}
	
	public ReturnData deleteDisease(Long id) {
		//查询疾病维表是否有该疾病
		icdDiseaseGaogeDao.deleteGaogeDisease(id);
	return ReturnUtil.success();
}
	
}
